import axios from 'axios'
import { Message } from 'element-ui' // MessageBox token超时再启用处理
import store from '@/store'
import { getToken } from '@/utils/auth'
const Base64 = require('js-base64').Base64
import qs from 'qs'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 60, // request timeout
  headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (config.url.indexOf('v1/login') != -1) {
      config.headers['Authorization'] = 'Basic ' + Base64.encode(store.getters.userinfo.username + ':' + store.getters.userinfo.password)
    }
    if (config.headers['Content-Type'] == 'application/x-www-form-urlencoded;charset=utf-8') {
      config.data = qs.stringify(config.data)
    }
    var hasToken = getToken()
    if (hasToken) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    let res = response.data
    //处理七牛上传年后返回增加code字段
    if (JSON.stringify(res).indexOf("bucket") != -1) {
      res.code = 1
    }
    if (res.code == 1) {
      return res
    } else if (res.code == 401) {
      Message({
        message: res.error || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      store.dispatch("user/logout")
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      console.log(res, "error")
      Message({
        message: res.error || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
